<?php

namespace App\Http\Middleware;

use App\Model\AdminUser;
use Closure;
use Illuminate\Support\Facades\Cache;

class CheckAccessToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $access_token=$token = isset($_SERVER['HTTP_X_ACCESS_SECURE_TOKEN'])?$_SERVER['HTTP_X_ACCESS_SECURE_TOKEN']:false;
        $time        = isset($_SERVER['HTTP_X_TIME'])?$_SERVER['HTTP_X_TIME']:false;
        $user_id     = isset($_SERVER['HTTP_X_ACCESS_USER'])?$_SERVER['HTTP_X_ACCESS_USER']:false;

        if(!$time || !$access_token || !$user_id){
            return response()->json(array('status'=>'401','error'=>'Forbidden, without the access_token,time,uid'));
        }
        $session_data = Cache::get(config('adminRedisPrefix').$user_id);
        if(empty($session_data)){
            return response()->json(array('status'=>'401','error'=>'Token has failed or Token has timeout'));
        }
        //用传过来的user_id 跟时间错 合法检验
        if(md5($session_data.$time) !== $access_token ){
            return response()->json(array('status'=>'401','error'=>'Token has failed or Token has timeout'));
        }
        //查询该用户信息
        $userModel = new AdminUser();
        $userInfo = $userModel->getAdminUserInfo('id => '.$user_id);
        //过滤超级用户
        if($userInfo['name'] != 'admin'){
//            //获取路由
//            $module=Request::instance()->module();
//            $controller=Request::instance()->controller();
//            $action=Request::instance()->action();
//            //判断路由是否存在与对应的权限中
//            $arpModel = new AdminRolePermission();
//            $permissions = $arpModel->getPermissions($userInfo['role_id']);
//            $currentRoute = $module.'/'.$controller.'/'.$action;
//            if(!in_array($currentRoute,$permissions)){
//                $resp = new \app\common\domain\Response('401','没有权限访问','');
//                return $resp;
//            }
        }
//        return $session_data;

        return $next($request);
    }
}
